package com.pilot.game.service;

import com.pilot.game.config.ApplicationProperties;
import com.pilot.game.security.SecurityUtils;
import com.qiniu.util.Json;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class TulinRobotService {

    private final Logger log = LoggerFactory.getLogger(TulinRobotService.class);
    private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");

    private final ApplicationProperties.Tulin properties;

    public TulinRobotService(ApplicationProperties properties) {
        this.properties = properties.getTulin();
    }

    public String talk(String msg) throws IOException {
        String userLogin = SecurityUtils.getCurrentUserLogin();
        Map<String, String> params = new HashMap<>();
        params.put("userid", userLogin);
        params.put("key", properties.getApiKey());
        params.put("info", msg);
        log.debug("request msg is: {}", msg);

        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(JSON_TYPE, Json.encode(params));
        Request request = new Request.Builder()
            .url(properties.getUrl())
            .post(body)
            .build();
        Response response = client.newCall(request).execute();
        return Json.decode(response.body().string()).get("text").toString();
    }

}
